package org.web.webdisplay.server.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.deser.std.DateDeserializers;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.web.base.domain.config.GlobalString2DateConvert;
import org.web.base.helper.DateHelper;

import java.io.IOException;
import java.util.Date;

@Configuration("webDisplayServerJacksonConfig")
public class JacksonConfig {

    @Bean("webDisplayServerObjectMapper")
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        // 基础配置
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // 忽略null属性
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // 忽略未知字段
        objectMapper.registerModule(new JavaTimeModule()); // 支持Java 8时间类型
        // 自定义Date反序列化器（支持多格式）
        SimpleModule dateModule = new SimpleModule();
        // 添加Date序列化器（后端→前端）
        dateModule.addSerializer(Date.class, new JsonSerializer<>() {
            @Override
            public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
                if (value == null) {
                    gen.writeNull();
                    return;
                }
                gen.writeString(DateHelper.formatDateSmart(value));
            }
        });

        dateModule.addDeserializer(Date.class, new DateDeserializers.DateDeserializer() {
            @Override
            public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
                String dateStr = p.getText().trim();
                // 定义支持的日期格式列表
                try {
                    return DateHelper.parseDateWithMultipleFormats(dateStr);
                } catch (Exception e) {
                    throw new IOException(e);
                }
            }
        });

        objectMapper.registerModule(dateModule);
        return objectMapper;
    }

    @Bean("webDisplayServerString2DateConvert")
    public GlobalString2DateConvert getGlobalString2DateConvert() {
        return new GlobalString2DateConvert();
    }

}